package com.ming.stringstudy.feedbacksystem.controller;

import com.ming.stringstudy.feedbacksystem.entity.Permission;
import com.ming.stringstudy.feedbacksystem.pojo.PageBean;
import com.ming.stringstudy.feedbacksystem.pojo.Result;
import com.ming.stringstudy.feedbacksystem.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author aming
 * @since 2025-01-19
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) Integer id,
                       @RequestParam(required = false) String permissionName) {
        try{
            Permission permission = new Permission();
            permission.setId(id);
            permission.setPermissionName(permissionName);
            PageBean pageBean = permissionService.page(page, pageSize, permission);
            return Result.success(pageBean);
        }catch (Exception e){
            return Result.error("查询失败");
        }
    }

    @PostMapping
    public Result addPermission(@RequestBody Permission permission) {
        try{
            int result = permissionService.addPermission(permission);
            if (result == 0){
                return Result.error("添加失败");
            }else {
                return Result.success("添加成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @PutMapping
    public Result updatePermission(@RequestBody Permission permission) {
        try {
            int result = permissionService.updatePermission(permission);
            if (result == 0){
                return Result.error("修改失败");
            }else {
                return Result.success("修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @DeleteMapping("/{ids}")
    public Result deletePermission(@PathVariable List<Integer> ids) {
        try {
            int result = permissionService.deletePermission(ids);
            if (result == 0){
                return Result.error("删除失败");
            }else {
                return Result.success("删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }
}
